﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Threading;
using System.IO;
using MyAspx.Framework.WebUnit.CodeZipTree;
using System.Text;

namespace WebUI.Services.CodeTree
{

    public enum OperationState
    {
        OK,
        Failed,
        IsExist,
        NotExist,
        InvalidCharacters,
        Null,
        Unknow,
        CannotDelete,
        NoFile
    }

    /// <summary>
    /// Summary description for FileOperation
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class FileOperation : System.Web.Services.WebService
    {

        [WebMethod]
        public OperationState CreateFolder(string dir)
        {

            dir = dir.ToOriginalPath();

            try
            {
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                    return OperationState.OK;
                }
                else
                {
                    return OperationState.IsExist;
                }
            }
            catch
            {
                return OperationState.Unknow;
            }
        }

        [WebMethod]
        public OperationState CreateFile(string dir,string text)
        {

            dir = dir.ToOriginalPath();

            try
            {
                string dirName = Path.GetDirectoryName(dir);

                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }

                using (StreamWriter sw = new StreamWriter(dir, false, Encoding.UTF8))
                {
                    sw.Write(text);
                }

                return OperationState.OK;
            }
            catch
            {
                return OperationState.Unknow;
            }
        }

        [WebMethod]
        public OperationState Delete(string dir)
        {
            try
            {
                foreach (string str in dir.Split(','))
                {
                    string path = str.ToOriginalPath();

                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    else if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true);  
                    }
                    else
                    {
                        return OperationState.IsExist;
                    }
                }
                return OperationState.OK;

            }
            catch
            {
                return OperationState.Unknow;
            }
        }

        [WebMethod]
        public string LoadFileText(string dir)
        {
            dir = dir.ToOriginalPath();

            if (Path.GetExtension(dir).Length <= 0) return "";

            try
            {
                string text= "";
                using (StreamReader sr = new StreamReader(dir, Encoding.UTF8))
                {
                    text = sr.ReadToEnd();
                }

                return text;
            }
            catch(Exception ex)
            {
                return ex.Message;
            }
        }

        [WebMethod]
        public OperationState Edit(string dir,string toDir)
        {
            dir = dir.ToOriginalPath(); toDir = toDir.ToOriginalPath();

            try
            {
                if (File.Exists(dir))
                {
                    File.Move(dir, toDir);
                    return OperationState.OK;
                }
                else if (Directory.Exists(dir))
                {
                    Directory.Move(dir, toDir);
                    return OperationState.OK;
                }
                else
                {
                    return OperationState.NotExist;
                }

            }
            catch
            {
                return OperationState.Unknow;
            }
        }

        [WebMethod]
        public OperationState Decompress(string[] files)
        {
            if (files.Count() <= 0) return OperationState.NoFile; 

            try
            {
                foreach (string file in files)
                {
                    string f = file.ToOriginalPath();
                    string gzip = Path.GetExtension(f);
                    if (gzip.ToLower() == ".gzip")
                    {
                        string currDirectory = Path.GetDirectoryName(f);
                        GZip.Decompress(currDirectory, currDirectory, Path.GetFileName(f));
                    }
                }

                return OperationState.OK;
            }
            catch
            {
                return OperationState.Unknow;
            }
        }

        [WebMethod]
        public OperationState CompressFiles(string[] files)
        {
            return Compress(files, new string[] { });
        }

        [WebMethod]
        public OperationState CompressDirectorys(string[] directorys)
        {
            return Compress(new string[] { }, directorys);
        }


        [WebMethod]
        public OperationState Compress(string[] files, string[] directorys)
        {

            if (files.Count() <= 0 && directorys.Count() <= 0) return OperationState.NoFile;

            IList<FileInfo> lists = new List<FileInfo>();
            IList<string> listsdir = new List<string>();

            string currDirectory = "";
            if (files.Count() > 0)
            {
                currDirectory = Path.GetDirectoryName(files[0].ToOriginalPath());
            }
            else if (directorys.Count() > 0)
            {
                var root = false;
                currDirectory = Explorer.GetPrevDirectory(directorys[0].ToOriginalPath(), ref root);
            }
            else
            {
                return OperationState.NoFile;
            }

            try
            {
                foreach (string str in files)
                {
                    lists.Add(new FileInfo(str.ToOriginalPath()));
                }

                foreach (string str in directorys)
                {
                    listsdir.Add(str.ToOriginalPath());
                }

                string[] dirs;
                if (directorys.Count() > 0)
                    dirs = listsdir.ToArray();
                else
                    dirs = new string[] { };

                GZip.Compress(lists.ToArray(), dirs, currDirectory, currDirectory, string.Concat(Guid.NewGuid().ToString().Replace("-", ""), ".gzip"));
                return OperationState.OK;

            }
            catch
            {
                return OperationState.Unknow;
            }
        }

    }
}
